package com.cy.web.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* Cookie工具类
* */

public class CookieUtil {

    /**
     * 设定cookie（多个重载方法）
     * @param response  响应对象
     * @param name      cookie名（key）
     * @param value     cookie值（value）
     * @param domain    域名
     * @param path      uri路径
     * @param maxAge    cookie存活时间
     */

    //全参方法
    public static void setCookie(HttpServletResponse response,
                                 String name,
                                 String value,
                                 String domain,
                                 String path,
                                 int maxAge) {
        //1.创建cookie对象
        Cookie cookie = new Cookie(name, value);

        //2.域名判断：有添加域名，无跳过
        if(domain != null) {
            cookie.setDomain(domain);
        }

        //3.设定cookie的uri
        cookie.setPath(path);

        //4.设定cookie的存活时间
        cookie.setMaxAge(maxAge);

        //5.将cookie添加至响应对象
        response.addCookie(cookie);
    }

    public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
        setCookie(response, name, value, null, "/", maxAge);
    }

    public static void setCookie(HttpServletResponse response, String name, String value) {
        setCookie(response, name, value, null, "/", 3600);
    }

    public static void setCookie(HttpServletResponse response, String name) {
        setCookie(response, name, "", null, "/", 3600);
    }

    /**
     * @param request
     * @param name
     * @return
     */
    public static String getCookie(HttpServletRequest request, String name) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    value = cookie.getValue();
                }
            }
        }
        return value;
    }

    /**
     * 移除cookie
     *
     * @param response  响应对象
     * @param name      cookie名
     * @return
     */
    public static void removeCookie(HttpServletResponse response, String name, String domain, String path) {
        setCookie(response, name, "", domain, path, 0);
    }

}
